require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")

require 'json'
podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}

ENV['RCT_NEW_ARCH_ENABLED'] = podfile_properties['newArchEnabled'] == 'true' ? '1' : '0'
ENV['EX_DEV_CLIENT_NETWORK_INSPECTOR'] = podfile_properties['EX_DEV_CLIENT_NETWORK_INSPECTOR']

platform :ios, '15.1'
prepare_react_native_project!
# Ensures that versions from Gemfile is respected
ensure_bundler!

install! 'cocoapods',
  :deterministic_uuids => false

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
  $RNFirebaseAsStaticFramework = true
end

# react_native_post_install:
# Disabled to fix SentryPrivate Xcode 15 build error
# - https://github.com/getsentry/sentry-react-native/issues/3322

# def react_native_post_install(installer)
# 	installer.pods_project.targets.each do |target|
#   		target.build_configurations.each do |config|
# 			if Gem::Version.new('9.0') > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'])
# 				config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = "12.0"
# 			end
# 			config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
#   		end
#  	end

# 	projects = installer.aggregate_targets
# 	  .map{ |t| t.user_project }
# 	  .uniq{ |p| p.path }
# 	  .push(installer.pods_project)

# 	arm_value = `/usr/sbin/sysctl -n hw.optional.arm64 2>&1`.to_i

# 	projects.each do |project|
# 	  project.build_configurations.each do |config|
# 		  if arm_value == 1 then
# 		    config.build_settings.delete("EXCLUDED_ARCHS[sdk=iphonesimulator*]")
# 		  else
# 		    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
# 		  end
# 	  end

# 	  project.save()
# 	end
# end

def common_target_logic
  podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}

  use_expo_modules!
	# config = use_native_modules!

  if ENV['EXPO_USE_COMMUNITY_AUTOLINKING'] == '1'
    config_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"];
  else
    config_command = [
      'node',
      '--no-warnings',
      '--eval',
      'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))',
      'react-native-config',
      '--json',
      '--platform',
      'ios'
    ]
  end

  config = use_native_modules!(config_command)

  use_frameworks! :linkage => ENV['USE_FRAMEWORKS'].to_sym if ENV['USE_FRAMEWORKS']

  # Pods for MetaMask
  pod 'ReactNativePayments', :path => '../node_modules/@metamask/react-native-payments/lib/ios/'

  # Pods for Push Notifications
  pod 'FirebaseCore', :modular_headers => true
  pod 'GoogleUtilities/NSData+zlib', :modular_headers => true

   # Comment the next line if you don't want to use dynamic frameworks
  # use_frameworks!
	pod 'Permission-BluetoothPeripheral', :path => '../node_modules/react-native-permissions/ios/BluetoothPeripheral'
  pod 'GzipSwift'

  # Pod for fixing react-native-quick-crypto issue: https://github.com/margelo/react-native-quick-crypto/issues/244
  pod 'OpenSSL-Universal', :modular_headers => true

  use_react_native!(
    :path => config[:reactNativePath],
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/..",
    :privacy_file_aggregation_enabled => podfile_properties['apple.privacyManifestAggregationEnabled'] != 'false',
    :hermes_enabled => true
  )
end

target 'MetaMask' do
  common_target_logic
end

target 'MetaMask-QA' do
  common_target_logic
end

target 'MetaMask-Flask' do
	common_target_logic
end

if ENV['EXPO_USE_COMMUNITY_AUTOLINKING'] == '1'
  config_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"];
else
  config_command = [
    'node',
    '--no-warnings',
    '--eval',
    'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))',
    'react-native-config',
    '--json',
    '--platform',
    'ios'
  ]
end

config = use_native_modules!(config_command)

post_install do |installer|
  react_native_post_install(
    installer,
    config[:reactNativePath],
    :mac_catalyst_enabled => false,
    :ccache_enabled => podfile_properties['apple.ccacheEnabled'] == 'true',
  )

  # Modify RCT-Folly Portability.h to disable coroutines
  Dir.glob(installer.sandbox.root + "RCT-Folly/folly/Portability.h") do |file|
    begin
      # First try to make the file writable
      system "chmod +w #{file}"

      contents = File.read(file)
      modified_contents = contents.gsub(/#define FOLLY_HAS_COROUTINES 1/, '#define FOLLY_HAS_COROUTINES 0')

      # Try writing with elevated privileges if needed
      if !File.writable?(file)
        system "sudo chmod +w #{file}"
      end

      File.write(file, modified_contents)

      # Optionally restore original permissions
      system "chmod -w #{file}"
    rescue => e
      Pod::UI.warn "Failed to modify Portability.h: #{e.message}"
    end
  end

  # This is necessary for Xcode 14, because it signs resource bundles by default
  # when building for devices.
  installer.target_installation_results.pod_target_installation_results
    .each do |pod_name, target_installation_result|
    target_installation_result.resource_bundle_targets.each do |resource_bundle_target|
      resource_bundle_target.build_configurations.each do |config|
        config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
      end
    end
  end
end
